import { ref, computed } from 'vue'
import { defineStore } from 'pinia'

// 商品管理仓库：基础信息 + 上下架状态 + 分类/品牌等元数据
export const useProductStore = defineStore('product', () => {
  const STORAGE_KEY = 'erppos_products'
  const productList = ref([])

  // 下拉元数据（可替换为后端接口）
  const categories = ref(['饮料', '食品', '日用品', '电子产品', '服装'])
  const brands = ref(['默认品牌', '可口可乐', '康师傅', '清洁用品', 'Apple'])

  // 初始化示例数据
  const initializeProducts = () => {
    const cached = localStorage.getItem(STORAGE_KEY)
    if (cached) {
      productList.value = JSON.parse(cached)
      return
    }
    productList.value = [
      {
        id: 'P001',
        code: 'SKU001',
        name: '可口可乐',
        category: '饮料',
        brand: '可口可乐',
        specification: '330ml',
        unit: '瓶',
        salePrice: 3.5,
        costPrice: 2.5,
        status: 'on', // on=上架, off=下架
        barcode: '690000000001',
        createdAt: new Date('2024-01-10').toISOString(),
        updatedAt: new Date('2024-01-15').toISOString(),
      },
      {
        id: 'P002',
        code: 'SKU002',
        name: '康师傅方便面',
        category: '食品',
        brand: '康师傅',
        specification: '袋装',
        unit: '袋',
        salePrice: 4.5,
        costPrice: 3.2,
        status: 'on',
        barcode: '690000000002',
        createdAt: new Date('2024-01-11').toISOString(),
        updatedAt: new Date('2024-01-14').toISOString(),
      },
      {
        id: 'P003',
        code: 'SKU003',
        name: '洗衣粉',
        category: '日用品',
        brand: '清洁用品',
        specification: '1kg',
        unit: '袋',
        salePrice: 18,
        costPrice: 12,
        status: 'off',
        barcode: '690000000003',
        createdAt: new Date('2024-01-12').toISOString(),
        updatedAt: new Date('2024-01-13').toISOString(),
      },
    ]
  }

  const persist = () => {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(productList.value))
  }

  const totalOnSale = computed(() => productList.value.filter(p => p.status === 'on').length)
  const totalOffSale = computed(() => productList.value.filter(p => p.status === 'off').length)

  // 查询与筛选
  const getFilteredProducts = (filters) => {
    return productList.value.filter(p => {
      if (filters.search) {
        const s = filters.search.toLowerCase()
        if (!p.name.toLowerCase().includes(s) && !p.code.toLowerCase().includes(s) && !(p.barcode || '').includes(filters.search)) {
          return false
        }
      }
      if (filters.category && p.category !== filters.category) return false
      if (filters.brand && p.brand !== filters.brand) return false
      if (filters.status && p.status !== filters.status) return false
      return true
    })
  }

  // 基础CRUD
  const addProduct = (data) => {
    const newProduct = {
      id: 'P' + Date.now(),
      code: data.code,
      name: data.name,
      category: data.category || '',
      brand: data.brand || '',
      specification: data.specification || '',
      unit: data.unit || '件',
      salePrice: Number(data.salePrice || 0),
      costPrice: Number(data.costPrice || 0),
      status: data.status || 'off',
      barcode: data.barcode || '',
      // 服装行业扩展字段（可选）
      styleNo: data.styleNo || '',
      color: data.color || '',
      size: data.size || '',
      season: data.season || '',
      year: data.year || '',
      createdAt: new Date().toISOString(),
      updatedAt: new Date().toISOString(),
    }
    productList.value.unshift(newProduct)
    persist()
    return newProduct
  }

  const updateProduct = (id, updates) => {
    const idx = productList.value.findIndex(p => p.id === id)
    if (idx === -1) return null
    productList.value[idx] = {
      ...productList.value[idx],
      ...updates,
      updatedAt: new Date().toISOString(),
    }
    persist()
    return productList.value[idx]
  }

  const deleteProduct = (id) => {
    const idx = productList.value.findIndex(p => p.id === id)
    if (idx === -1) return false
    productList.value.splice(idx, 1)
    persist()
    return true
  }

  // 上下架
  const toggleStatus = (id) => {
    const p = productList.value.find(x => x.id === id)
    if (!p) return null
    p.status = p.status === 'on' ? 'off' : 'on'
    p.updatedAt = new Date().toISOString()
    persist()
    return p.status
  }

  const batchToggleStatus = (ids, target) => {
    ids.forEach(id => {
      const p = productList.value.find(x => x.id === id)
      if (p) {
        p.status = target || (p.status === 'on' ? 'off' : 'on')
        p.updatedAt = new Date().toISOString()
      }
    })
    persist()
  }

  const exportProducts = (list = null) => {
    const rows = (list || productList.value).map(p => [
      p.code, p.name, p.category, p.brand, p.specification, p.unit, p.salePrice, p.costPrice, p.status, p.barcode,
    ])
    const headers = ['编码', '名称', '类别', '品牌', '规格', '单位', '售价', '成本', '状态', '条码']
    const csv = [headers.join(','), ...rows.map(r => r.join(','))].join('\n')
    const blob = new Blob(['\ufeff' + csv], { type: 'text/csv;charset=utf-8;' })
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    link.href = url
    link.download = `商品数据_${new Date().toISOString().slice(0,10)}.csv`
    link.click()
    URL.revokeObjectURL(url)
  }

  return {
    // state
    productList,
    categories,
    brands,

    // getters
    totalOnSale,
    totalOffSale,

    // actions
    initializeProducts,
    getFilteredProducts,
    addProduct,
    updateProduct,
    deleteProduct,
    toggleStatus,
    batchToggleStatus,
    exportProducts,
  }
})


